# Copyright 2009 Lee Harr
#
# This file is part of Acromania.
#
# Acromania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Acromania is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Acromania.  If not, see <http://www.gnu.org/licenses/>.


import random
import bisect
import string


def choice_weighted(seq, weights):
    'return a random choice from seq, choosing heavier weighted items more.'

    weightstotal = float(sum(weights))

    cum_norm_weights = [0.0]*len(weights)
    for i in xrange(len(weights)):
        cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/weightstotal

    return seq[bisect.bisect(cum_norm_weights, random.random())]



items = ['A', 'B', 'C', 'D']
weights = [10, 20, 30, 150]


def test_choice_weighted(n):
    counter = {}
    weightstotal = float(sum(weights))
    for item in items:
        counter[item] = 0
    for t in xrange(n):
        result = choice_weighted(items, weights)
        counter[result] += 1
    for i, item in enumerate(items):
        fmt = '%s: %+4s %.5s %.5s'
        rawcount = counter[item]
        desired = weights[i]/weightstotal
        actual = counter[item]/float(n)
        print fmt % (item, rawcount, desired, actual)


from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    for item in b: break
    return izip(a, b)


def scrubword(word):
    'return word with any non-letters removed from beginning and end of word.'

    uplow = string.uppercase+string.lowercase

    scrubch = []
    foundletters = False
    for ch in word:
        if ch in uplow or foundletters:
            foundletters = True
            scrubch.append(ch)
    scrubch.reverse()
    scr = ''.join(scrubch)
    scrubch = []
    foundletters = False
    for ch in scr:
        if ch in uplow or foundletters:
            foundletters = True
            scrubch.append(ch)
    scrubch.reverse()
    scrub = ''.join(scrubch)

    return scrub.lower()


def makeconf():
    'create an empty conf file'

    conf_file = 'conf.py'

    import os
    if os.path.exists(conf_file):
        print 'conf.py already exists'
        raise SystemExit

    contents = '''\
from conf_defaults import *

# Make configuration changes here.
# See conf_defaults.py for available parameters.

'''

    f = open(conf_file, 'w')
    f.write(contents)
    f.close()

    print 'conf.py created'
    print 'please check configuration.'
